#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 1000005
#define LL long long

int n,x,l,r; LL ans;
int tot,point[N],nxt[N*2],v[N*2],s[N*2];
LL val[N],f[N][2];
bool flag,vis[N];

void addedge(int x,int y)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;
    ++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x;
}
void dfs(int x,int fa)
{
    vis[x]=true;
    for (int i=point[x];i!=-1&&(!flag);i=nxt[i])
        if (v[i]!=fa)
        {
            if (vis[v[i]])
            {
                l=x,r=v[i]; s[i]=s[i^1]=-1;
                flag=true;
                break;
            }
            dfs(v[i],x);
        }
}
void treedp(int x,int fa,int cant)
{
    vis[x]=true;
    if (x!=cant) f[x][1]=val[x];
    else f[x][1]=0;
    f[x][0]=0;
    for (int i=point[x];i!=-1;i=nxt[i])
        if (v[i]!=fa&&s[i]!=-1)
        {
            treedp(v[i],x,cant);
            f[x][0]+=max(f[v[i]][0],f[v[i]][1]);
            f[x][1]+=f[v[i]][0];
        }
}

int main()
{
    tot=-1; memset(point,-1,sizeof(point)); memset(nxt,-1,sizeof(nxt));
    scanf("%d",&n);
    for (int i=1;i<=n;++i)
    {
        scanf("%lld%d",&val[i],&x);
        addedge(x,i);
    }
    for (int i=1;i<=n;++i)
        if (!vis[i])
        {
            flag=false;
            dfs(i,0);
            LL Max=0;
            treedp(l,0,r);
            Max=max(f[l][0],f[l][1]);
            treedp(r,0,l);
            Max=max(Max,max(f[r][0],f[r][1]));
            ans+=Max;
        }
    printf("%lld\n",ans);
}
